package com.example.apiclientsdk.apiclient;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.example.apiclientsdk.model.User;
import com.example.apiclientsdk.utils.SignUtils;


import java.util.HashMap;
import java.util.Map;

public class ApiClient {

//    public static final String GATEWAY_HOST = "http://192.168.200.128:8555";
    public static final String GATEWAY_HOST = "http://localhost:8555";

    private String accessKey;
    private String secretKey;

    public ApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    public String getNameByGet(String name) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        String s = HttpUtil.get(GATEWAY_HOST+"/api/name/", map);
        return s;
    }

    public String getNameByPost(String name) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("name", name);
        String s = HttpUtil.post(GATEWAY_HOST+"/api/name/", map);
        return s;
    }

    public String getUsernameByPost(User user) {
        String jsonStr = JSONUtil.toJsonStr(user);
        HttpResponse execute = HttpUtil.createPost(GATEWAY_HOST+"/api/name/user")
                .addHeaders(getHeaderMap(jsonStr))
                .body(jsonStr)
                .execute();
        System.out.println(execute.getStatus());
        String body = execute.body();
        return body;
    }

    public Map<String, String> getHeaderMap(String body) {
        HashMap<String, String> map = new HashMap<String,String>();
        map.put("nonce", RandomUtil.randomNumbers(4));
        map.put("body", body);
        map.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        map.put("sign", SignUtils.genSign(body, secretKey));
        map.put("accessKey", accessKey);
        return map;
    }

}
